const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
//导入jwt
const jwt = require('jsonwebtoken');

// 验证JWT
const { verifyToken, checkRole } = require('../auth');

// const SECRET_KEY = 'guanggu_traffic@cn.key'; // 删除硬编码
const { JWT_SECRET } = process.env;

// 定义存储引擎
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.resolve(__dirname, '../../public/avatarImg'));
  },
  filename: function (req, file, cb) {
    let extname = path.extname(file.originalname);
    cb(null, Date.now() + extname);
  },
});
const upload = multer({ storage: storage });
const {
  addUser,
  findUserByUsername,
  getUsersAll,
  deleteUser,
  upPassword,
  loginUser,
  upUserInfo,
  upAvatar,
  resetPassword,
} = require('../../services/index');

// 登录
router.post('/login', async (req, res) => {
  let result = await loginUser(req.body);
  // console.log(result);
  if (result.status === 1) {
    // 1. 登录成功，生成令牌
    let user = result.user.dataValues;
    const token = jwt.sign(
      {
        id: user.id,
        username: user.username,
        type: user.type,
      },
      JWT_SECRET,
      { expiresIn: '2h' } // 设置令牌过期时间
    );
    // 2. 返回成功响应
    res.json({
      status: 1,
      msg: '登录成功',
      token, // 返回给客户端的令牌
      user: {
        // 返回部分用户信息（不要返回密码！）
        id: user.id,
        username: user.username,
        type: user.type,
      },
    });
  } else {
    res.json(result);
  }
});

//查询所有的用户
router.get('/', verifyToken, checkRole(['admin']), async (req, res) => {
  let result = await getUsersAll();
  res.json(result);
});

//根据用户名查询用户
router.get('/getbyname', verifyToken, async (req, res) => {
  //req里面没有拿到携带的查询参数 使用query
  let { username, type } = req.query;
  let result = await findUserByUsername(username, type);
  result.data.dataValues.password = '******';
  res.json(result);
});

//增加用户
router.post('/addUser', async (req, res) => {
  let result = await addUser(req.body);
  res.json(result);
});

//修改用户信息
router.post('/updateUser', verifyToken, async (req, res) => {
  // console.log(req.body);
  let result = await upUserInfo(req.body);
  res.json(result);
});

//修改密码
router.post('/updatePassword', verifyToken, async (req, res) => {
  // console.log(req.body);
  let result = await upPassword(req.body);
  res.json(result);
});

//上传头像
router.post(
  '/uploadAvatar',
  verifyToken,
  upload.single('file'),
  async (req, res) => {
    // 添加文件存在性检查
    if (!req.file) {
      return res.status(400).json({
        msg: '文件上传失败',
        status: 0,
      });
    }
    // 修正后的URL生成逻辑
    let url = `http://localhost:3001/avatarImg/${req.file.filename}`;
    let result = await upAvatar(req.body, url);
    if (result.status === 1) {
      res.json({
        msg: '上传成功',
        status: 1,
        url: url, // 返回完整的URL
      });
    } else {
      res.json(result);
    }
  }
);

///删除用户
router.delete('/deleteUser', verifyToken, async (req, res) => {
  let result = await deleteUser(req.query);
  res.json(result);
});

//重置密码
router.post(
  '/resetPassword',
  verifyToken,
  checkRole(['admin']),
  async (req, res) => {
    console.log(req.body); // 确保req.body包含了username和type字段
    let result = await resetPassword(req.body);
    res.json(result);
  }
);

module.exports = router;
